package com.appspot.modutajataja;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.view.WindowManager;
import android.webkit.WebSettings.RenderPriority;
import android.webkit.WebView;

public class TouchGameWebview extends Activity {
	
	WebView webView;
	private final Handler handler = new Handler();
	final int htmlWidth = 960;
	MediaPlayer mediaPlayer;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.touch_game_webview);
		
		getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
		
		double width = ((WindowManager)getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay().getWidth();
		int scalePecent = (int)(width/htmlWidth*98);
		System.out.println(scalePecent);
		
		webView = (WebView)findViewById(R.id.touch_game_webView);
		webView.addJavascriptInterface(new AndroidBridge(), "HybridApp");
		
		webView.getSettings().setRenderPriority(RenderPriority.HIGH);
		
		webView.getSettings().setJavaScriptEnabled(true);	
		webView.getSettings().setLoadWithOverviewMode(true);
		
		// =====================================================
		webView.getSettings().setDomStorageEnabled(true);
		webView.getSettings().setLoadsImagesAutomatically(true);
        webView.getSettings().setSupportZoom(false);
        webView.getSettings().setAllowFileAccess(true);
        webView.getSettings().setSupportMultipleWindows(false);
        webView.getSettings().setAppCacheEnabled(true);
        webView.getSettings().setAppCachePath("");
        // =====================================================
        
		webView.setInitialScale(scalePecent);
		webView.loadUrl("file:///android_asset/game/touch/touch_game.html");
	}
	
	private class AndroidBridge {
		public void gameOver(final String arg) {
			handler.post(new Runnable(){
				@Override
				public void run() {					
					startActivity(new Intent(TouchGameWebview.this, GameScore.class));
					TouchGameWebview.this.finish();
				}	
			});
		}
	}

	@Override
	protected void onResume() {
		super.onResume();
		mediaPlayer = MediaPlayer.create(this, R.raw.touch_game);
		mediaPlayer.setLooping(true);
		mediaPlayer.start();
	}
	
	@Override
	protected void onPause() {
		super.onPause();
		webView.destroy();
		webView = null;
		
		mediaPlayer.stop();
	}
};